package cn.hr.controller;

import java.util.Date;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.hr.pojo.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import cn.hr.utils.Constants;
import cn.hr.service.SysUserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录,注销控制器
 *
 * @author MO
 */
@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private SysUserService userService;

    @RequestMapping("/login")
    public String showLogin() {
        return "login";
    }

    @RequestMapping("/home")
    public String showHome(HttpServletRequest request) {
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("当前登陆用户：" + user.getUsername());
        System.out.println("当前登录用户角色:" + ((GrantedAuthority) user.getAuthorities().toArray()[0]).getAuthority());
        request.setAttribute("msg", "成功");
        request.getSession().setAttribute(Constants.USER_SESSION, user);
        return "forward:/sys/mission/list";
    }

    @RequestMapping("/login/error")
    public String loginError(HttpServletRequest request, Model model) {
        AuthenticationException exception = (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        model.addAttribute("ex", exception.toString());
        model.addAttribute("msg", "登录失败");
        return "login";
    }

    @RequestMapping("/admin")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String printAdmin() {
        return "如果你看见这句话，说明你有ROLE_ADMIN角色a权限";
    }

    @RequestMapping("/user")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_USER')")
    public String printUser() {
        return "如果你看见这句话，说明你有ROLE_USER角色u权限";
    }

    @RequestMapping("/date")
    public String date(@RequestParam("date") String date) {
        System.out.println(date);
        return "";
    }

}
